package com.atguigu.spzx.manager.Interceptor;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.util.LoginAuthUtil;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

/**
 * @author syh
 * @create 2023-08-15 9:50
 */
@Component
public class LoginAuthInterceptor implements HandlerInterceptor {
    @Resource
    StringRedisTemplate stringRedisTemplate;

    public static final ThreadLocal<SysUser> threadLocal=new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果是预检请求直接放行
        if ("OPTIONS".equals(request.getMethod())){
            return true;
        }
        //如果没有token拒绝
        String token = request.getHeader("token");
        if (!StringUtils.hasLength(token)){
            genResponse(response,ResultCodeEnum.LOGIN_ACCESS_ERROR);


            return false;
        }
        //如果有token过期了，拒绝
        String sysUserInfoJson =  stringRedisTemplate.opsForValue().get("user:login:" + token);
        if (!StringUtils.hasLength(sysUserInfoJson)){
            genResponse(response,ResultCodeEnum.LOGIN_EXPIRE_ERROR);

            return false;
        }
        //将校验登录状态查询到的sysUserInfoJson,交给搜徐的业务使用，后续业务无需再查询数据了
        LoginAuthUtil.set(JSON.parseObject(sysUserInfoJson,SysUser.class));

        return true;
    }
//构建响应报文
    private static void genResponse(HttpServletResponse response,ResultCodeEnum codeEnum) throws IOException {
        //响应状态码
        response.setStatus(HttpServletResponse.SC_OK);//响应报文的状态码
        //响应头(设置响应体内容的格式类型)
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        //响应体
        Result result = Result.build(null,codeEnum);
        String jsonString = JSON.toJSONString(result);
        response.getWriter().print(jsonString);//将json写入到响应体
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       //移除ThreadLocal中的缓存，不移除会造成内存泄露（OOM）
        LoginAuthUtil.remove();
        // HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
